package com.ziq.zcamp.post

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.model.LatLng
import com.blankj.utilcode.util.GsonUtils
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter
import com.facebook.imagepipeline.request.ImageRequest
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.*
import com.ziq.base.utils.permission.PermissionUtil
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.place.CampListItem
import com.ziq.zcamp.bean.post.CampInfo
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.databinding.FragmentSelectLocationCampBinding
import com.ziq.zcamp.databinding.ItemSelectCampBinding
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.MapUtil
import com.ziq.zcamp.view.StatusView
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SelectLocationCampFragment : BaseFragment(R.layout.fragment_select_location_camp){

    private val binding: FragmentSelectLocationCampBinding? by binding()
    val mViewModel: SelectLocationCampFragmentViewModel by viewModels()

    private var adapter : CampAdapter? = null
    private var campInfo: CampListItem? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    fun selectLocationTabViewModel() : SelectLocationTabViewModel?{
        if(activity != null && activity is SelectLocationTabActivity){
            return (activity as SelectLocationTabActivity).mViewModel
        }
        return null
    }

    var isResume = false
    private var isFirst = true
    override fun onResume() {
        super.onResume()
        isResume = true
        if (isFirst){
            isFirst = false
            init()
        }
    }

    fun init(){
        binding?.recycleView?.layoutManager = LinearLayoutManager(context)
        adapter = CampAdapter(context)
        binding?.recycleView?.adapter = adapter
        mViewModel.statusShow.observe(this, Observer<Int> {
            when(it){
                StatusView.IDLE -> {
                    binding?.statusView?.setStatus(StatusView.IDLE)
                }
                StatusView.LOADING -> {
                    binding?.statusView?.setStatus(StatusView.LOADING)
                }
                StatusView.NO_DATA -> {
                    binding?.statusView?.setStatus(
                        StatusView.NO_DATA,
                        isCenter = false,
                        marginTop = 86.dp,
                        imgSrc = R.drawable.pic_no_content_camp,
                        imgWidth = 235.dp,
                        imgHeight = 151.dp,
                        msg = "暂无相关内容哦～"
                    )
                }
                StatusView.NET_ERROR -> {
                    binding?.statusView?.setStatus(StatusView.NET_ERROR, updateActionBtn = { btn ->
                        btn.click {
                            mViewModel.onRefresh(true)
                        }
                    })
                }
            }
        })

        mViewModel.listRequestFinished.observe(this, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.finishRefresh()
                binding?.refreshLayout?.finishLoadMore()
            }
        })

        mViewModel.listHasMore.observe(this, Observer<Boolean> {
            if(it){
                binding?.refreshLayout?.resetNoMoreData()
            } else {
                binding?.refreshLayout?.setNoMoreData(true)
            }
        })

        mViewModel.list.observe(this, Observer<MutableList<CampListItem>> {
            adapter?.setData(it)
        })

        binding?.refreshLayout?.setOnRefreshListener {
            mViewModel.onRefresh(false)
        }
        binding?.refreshLayout?.setOnLoadMoreListener {
            mViewModel.onLoadMore()
        }
        binding?.root?.post {
            getLocation()
        }

        selectLocationTabViewModel()?.keyword?.observe(this) {
            mViewModel.keywordForReq = it
            mViewModel.onRefresh(false)
        }
        selectLocationTabViewModel()?.campInfo?.observe(this) {
            campInfo = it
            adapter?.notifyDataChanged()
        }
    }

    override fun onPause() {
        super.onPause()
        isResume = false
    }

    @SuppressLint("CheckResult")
    fun getLocation(){
        binding?.statusView?.setStatus(StatusView.LOADING)
        PermissionUtil.requestLocationPermission(requireActivity(), onGrant = {
            MapUtil.getCurrentLocation(callback = {
                if(mViewModel.myLatLng == null){
                    mViewModel.myLatLng = LatLng(it.latitude, it.longitude)
                    mViewModel.onRefresh(true)
                }
            }, onFail = {
                mViewModel.onRefresh(true)
            })
        }, onReject = {
            mViewModel.onRefresh(true)
        }, onRemind = {
            mViewModel.onRefresh(true)
        })
    }

    inner class CampAdapter(context: Context?) : GroupedRecyclerViewAdapter(context){

        private var dataList = mutableListOf<CampListItem>()
        fun setData(list: MutableList<CampListItem>) {
            dataList = list
            notifyDataSetChanged()
        }

        override fun getGroupCount(): Int {
            return 1
        }

        override fun getChildrenCount(groupPosition: Int): Int {
            return dataList.size
        }

        override fun hasHeader(groupPosition: Int): Boolean {
            return false
        }

        override fun hasFooter(groupPosition: Int): Boolean {
            return false
        }

        override fun getHeaderLayout(viewType: Int): Int {
            return R.layout.item_select_camp_header
        }

        override fun getChildLayout(viewType: Int): Int {
            return R.layout.item_select_camp
        }

        override fun getFooterLayout(viewType: Int): Int {
            return 0
        }

        override fun onBindHeaderViewHolder(holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?, groupPosition: Int) {
        }


        override fun onBindChildViewHolder(
            holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?,
            groupPosition: Int,
            childPosition: Int
        ) {
            holder?.let {
                val binding = ItemSelectCampBinding.bind(holder.itemView)
                val item = dataList[childPosition]
                binding.name.text = "${item.campName}"
                var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                if (item.pictures?.isNotEmpty() == true){
                    item.pictures?.let {
                        imageList = GsonUtils.fromJson(it, GsonUtils.getListType(ImageInfo::class.java))
                    }
                }
                val imageInfo = imageList.getOrNull(0)
                ImageUtil.updateImageFromNetwork(binding.image, imageInfo?.url?:"", ImageRequest.CacheChoice.DEFAULT)
                binding.status.isSelected = item.id == campInfo?.id
                holder.itemView.click {
                    selectLocationTabViewModel()?.campInfo?.postValue(item)
                    selectLocationTabViewModel()?.poiItem?.postValue(null)
                }
            }
        }

        override fun onBindFooterViewHolder(holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?, groupPosition: Int) {
        }

    }
}